<template>
  <div class="energyRecord">
    <!-- 区域 -->
    <div class="area">
      <el-card shadow="never" class="box-card">
        <div slot="header" class="clearfix">
          <!-- <span>区域选择</span> -->
          <el-tabs v-model="fz_qy_activeName" @tab-click="fz_qy_handleClick">
              <el-tab-pane label="区域选择" name="first"></el-tab-pane>
              <el-tab-pane label="分组选择" name="second"></el-tab-pane>
            </el-tabs>
        </div>

        <!-- <el-input
          placeholder="输入关键字进行过滤"
          clearable
          v-model="filterText"
        >
        </el-input>
        <div class="areaContent">
          <el-tree
            ref="tree"
            :expand-on-click-node="false"
            :highlight-current="true"
            default-expand-all
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
          >
            <template slot-scope="{ node }">
              <span
                style="font-size: 14px"
                class="custom-tree-node"
                :title="node.label"
                >{{ node.label }}</span
              >
            </template>
          </el-tree>
        </div> -->
        <div v-if="fz_qy_activeName == 'first'">
            <el-input
              placeholder="输入关键字进行过滤"
              clearable
              v-model="filterText"
            >
            </el-input>
            <div class="areaContent">
              <el-tree
                ref="tree"
                :expand-on-click-node="false"
                :highlight-current="true"
                default-expand-all
                :data="treeData"
                :props="defaultProps"
                @node-click="handleNodeClick"
                :filter-node-method="filterNode"
              >
                <template slot-scope="{ node }">
                  <span
                    style="font-size: 14px"
                    class="custom-tree-node"
                    :title="node.label"
                    >{{ node.label }}</span
                  >
                  <!-- <span>{{ node }}</span> -->
                </template>
              </el-tree>
            </div>
          </div>
          <div v-if="fz_qy_activeName == 'second'">
            <el-input
              placeholder="输入关键字进行过滤"
              clearable
              v-model="filterText1"
              @input="inputFn"
            >
            </el-input>
            <div class="areaContent">
              <el-tree
                ref="tree1"
                :props="defaultProps1"
                :highlight-current="true"
                :data="meterTitleList1"
                @node-click="handleNodeClick"
              >
                <span
                  style="font-size: 14px;"
                  class="custom-tree-node"
                  slot-scope="{ node, data }"
                >
                  {{ data.groupName }}
                </span>
              </el-tree>
            </div>
          </div>
      </el-card>
    </div>
    <div class="record">
      <!-- 搜索框 -->
      <div class="search">
        <div class="rightSearch">
          <el-select  v-model="meterType" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            class="elInput"
            placeholder="名称"
            clearable
            prefix-icon="el-icon-search"
            v-model="meterName"
          >
          </el-input>
          <el-input
            class="elInput"
            placeholder="表号"
            clearable
            prefix-icon="el-icon-search"
            v-model="meterNumber"
          >
          </el-input>
          <el-input
            class="elInput"
         
            placeholder="地址"
            clearable
            prefix-icon="el-icon-search"
            v-model="meterAddress"
          >
          </el-input>
          <!-- <el-date-picker
            :picker-options="pickerOptions"
            @change="change"
            :clearable="false"
            v-model="time"
            type="monthrange"
            align="center"
            range-separator="-"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="yyyy-MM"
          >
          </el-date-picker> -->
          <el-date-picker
          clearable
          @blur="time_blur"
            style="width: 330px;"
            v-model="time"
            @change="change"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
        </el-date-picker> 

          <el-button
            type="primary"
            @click="out"
            :disabled="tableData.length !== 0 ? false : true"
            >导出</el-button
          >
          <el-button type="primary" icon="el-icon-search" @click="search"
              >搜索</el-button
            >
        </div>
      </div>
      <!-- 表格数据 -->
      <div class="table">
        <el-table
          :show-overflow-tooltip="true"
          :data="tableData"
          ref="isExpand"
          height="calc(100%-10rem)"
          v-loading="loading"
          border
          highlight-current-row
          stripe
          style="width: 100%"
        >
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>
          <el-table-column align="center" prop="meterNumber" label="设备表号">
            <template slot-scope="scope">
              <el-popover
                placement="top"
                trigger="hover"
                :content="scope.row.meterNumber"
              >
                <span slot="reference" class="twoLineCls">{{
                  scope.row.meterNumber
                }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="meterName" label="设备名称">
          </el-table-column>
          <el-table-column align="center" prop="meterAddress" label="设备地址">
          </el-table-column>
          <el-table-column align="center" prop="elecUseCount" :label="meterType == 1?'用电量':'用水量'">
          </el-table-column>
          <el-table-column
            align="center"
            prop="elecSurplusCount"
            :label="meterType == 1 ?'剩余电量':'剩余水量'"
          >
          </el-table-column>
          <el-table-column align="center" prop="readingTime" label="抄表时间">
            <template slot-scope="scope">
              <el-popover
                placement="top"
                trigger="hover"
                :content="scope.row.readingTime"
              >
                <span slot="reference" class="twoLineCls">{{
                  scope.row.readingTime
                }}</span>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          v-show="tableData.length !== 0"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 30, 50, 70, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getQuantitiesRecordApi, quantitiesOutApi } from "../../api/devive";
import { getOrzApi } from "../../api/orz";
import { getGroupApi } from "@/api/group";

export default {
  data() {
    return {
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
      },
      meterType: 1,
      options: [
        {
          label: "电表",
          value: 1,
        },
        {
          label: "水表",
          value: 2,
        },
      ],
      time: "",
      startDate: "",
      endDate: "",
      meterName: "",
      meterNumber: "",
      meterAddress: "",
      orzId: "",
      pageNum: 1,
      pageSize: 10,
      total: null,
      filterText: "",
      treeData: [],
      defaultProps: {
        children: "children",
        label: "orzName",
      },
      tableData:[],
      loading: false,
      fz_qy_activeName: "first", // 区域选择、分组选择切换后绑定的状态值
      treeData: [],
      meterTitleList1: [],
      filterText1: "",
      
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getOrz();
    this.getTime();
    this.getQuantities(
      this.pageNum,
      this.pageSize,
      this.startDate,
      this.endDate,
      "",
      this.meterName,
      this.meterNumber,
      this.meterAddress,
      this.orzId,
      this.meterType,this.groupId
    );
  },
  methods: {
    out() {
      let loading = this.$loading({
        lock: true,
        text: "正在导出...",
      });
      quantitiesOutApi(
        this.pageNum,
        this.pageSize,
        this.startDate,
        this.endDate,
        "",
        this.meterName,
        this.meterNumber,
        this.meterAddress,
        this.orzId,
        this.meterType
      )
        .then((res) => {
          if (
            res.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          ) {
            let blob = new Blob([res], { type: "application/octet-stream" });
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            link.setAttribute("download", "能耗报表.xlsx");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            loading.close();
          }
        })
        .catch(() => {
          loading.close();
        });
    },
    input() {
      this.pageNum = 1;
      this.search();
    },
    search() {
      this.getQuantities(
        this.pageNum,
        this.pageSize,
        this.startDate,
        this.endDate,
        "",
        this.meterName,
        this.meterNumber,
        this.meterAddress,
        this.orzId,
        this.meterType,this.groupId
      );
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    getMonthDays(year, month) {
      var thisDate = new Date(year, month, 0); //当天数为0 js自动处理为上一月的最后一天
      return thisDate.getDate();
    },
    // getTime() {
    //   let year = new Date().getFullYear();
    //   let month = new Date().getMonth() + 1;
    //   if (month < 10) {
    //     month = "0" + month;
    //   }
    //   let last = this.getMonthDays(year, month);
    //   let date1 = `${year}-${month}-01`;
    //   let date2 = `${year}-${month}-${last}`;
    //   this.time = [date1, date1];
    //   this.startDate = date1;
    //   this.endDate = date2;
    // },
    getTime() {
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      }
      let last = this.getMonthDays(year, month);
      let date1 = `${year}-${month}-01`;
      let date2 = `${year}-${month}-${last}`;
      // this.time = [date1, date1];
      this.time = [date1, date2];
      this.startDate = date1;
      this.endDate = date2;
    },
        // 时间选择器失去焦点触发方法
        time_blur() {
console.log('失去交电',this.startDate,this.endDate);

    },
    change() {
      // console.log("e", e);
        console.log("this.time", this.time);
        if (this.time != null) {
          this.startDate = this.time[0];
          this.endDate = this.time[1];
          console.log("时间变化了", this.time);
        } else {

          this.getTime()
        }
      this.pageNum = 1;
      // this.search();
    },
    // 获取记录
    getQuantities(
      pageNum,
      pageSize,
      startDate,
      endDate,
      meterId,
      meterName,
      meterNumber,
      meterAddress,
      orzId,
      meterType,groupId
    ) {
      this.loading = true;
      getQuantitiesRecordApi(
        pageNum,
        pageSize,
        startDate,
        endDate,
        meterId,
        meterName,
        meterNumber,
        meterAddress,
        orzId,
        meterType,groupId
      ).then((res) => {
        if (res.code == 200) {
          this.loading = false;
          this.tableData = res.data.rows;
          this.total = res.data.total;
        }
      });
    },
    // 电表分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.search();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.search();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.orzName.indexOf(value) !== -1;
    },
    getOrz() {
      getOrzApi().then((res) => {
        if (res.code == 200) {
          this.treeData = [
            {
              orzName: "全部",
              orzId: "",
              children: [...res.data],
            },
          ];
        }
      });
    },
    handleNodeClick(e) {
      // this.orzId = e.orzId;
      this.pageNum = 1;
      this.pageSize = 10;
      // 区域选择
      if (this.fz_qy_activeName == "first") {
        this.orzId = e.orzId;
      }
      // 分组选择
      else {
        if (e.groupId == "" || e.groupId == 1 || e.groupId == 2) {
          this.groupId = "";
        } else {
          this.groupId = e.groupId;
        }
      }
      this.search();
    },
        // 初始化分组列表
        getGroup() {
      this.loading = true;
      let that = this;
      that.meterTitleList = [
        {
          groupId: "",
          groupName: "全部"
          // disabled:true
        }
      ];
      that.meterTitleList1 = [
        {
          groupId: "",
          groupName: "全部"
          // disabled:true
        }
      ];
      that.meterTitleList2 = [
        {
          groupId: "",
          groupName: "全部"
          // disabled:true
        }
      ];

      getGroupApi().then(res => {
        if (res.code == 200) {
          console.log("获取分组", res);
          /* 
             this.treeData = [
            {
              orzName: "全部",
              orzId: "",
              children: res.data == null ? [] : [...res.data] // 解决数据为null时后台报错问题(9-13)
            }
          
          */
          if (res.data.length !== 0) {
            that.meterTitleList.push(...res.data);
            that.meterTitleList1.push(...res.data);
            // 判断是首页还是批量里面的分组切换避免重复渲染
            that.meterTitleList2.push(...res.data);
            console.log("6", that.meterTitleList);
            console.log("meterTitleList2", that.meterTitleList2);
          }

          this.loading = false;
        }
      });
    },
    
    fz_qy_handleClick(e) {
      console.log("切换分组和区域tab", e);
      // 判断点击的是区域选择还是分组选择
      if (e.name == "first") {
        this.groupId = "";
        this.getOrz();
      } else {
        console.log("走分组选择");
        this.orzId = "";
        this.getGroup();
      }
    },
    // 监听输入框变化的事件---分组选择  用户输入后过滤数据方法
    inputFn(val) {
      console.log("输入框输入了什么", val);
      let arr = [];
      this.meterTitleList.filter(v => {
        if (v.groupName.indexOf(val) !== -1) {
          console.log("进来了", val);

          arr.push(v);
        } else {
          console.log("进来了123131", val);
        }
        this.meterTitleList1 = arr;
      });
    }

  },
};
</script>

<style lang="scss" scoped>
.energyRecord {
  padding-top: 15px;
  padding: 0 15px;
  height: calc(100vh - 100px);
  display: flex;
  justify-content: space-around;
  .area {
    width: 15%;
    height: 90%;
    .el-card {
      height: 100%;
      .custom-tree-node {
        text-align: left;
        width: calc(100% - 4px);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        min-width: auto;
        padding: 4px 26px 4px 2px;
        border-radius: 4px;
      }
    }
  }
  .record {
    width: 80%;
    height: 90%;
    padding: 1%;
    background: #fff;
    .search {
      margin-bottom: 1%;

      .rightSearch {
        display: flex;
        justify-content: space-around;
        align-items: center;
        width: 100%;
        .el-select {
          width: 15%;
        }
        .elInput {
          width: 15%;
        }
        .el-date-editor {
          width: 25%;
        }
      }
    }
    .table {
      height: 75%;

      .el-table {
        height: 100%;
      }

      .el-pagination {
        text-align: center;
        margin-top: 20px;
      }
    }
  }
  .previewDialog {
    .el-dialog {
      height: 60%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      .el-dialog__body {
        height: 90%;
      }
    }
  }
}
</style>
<style>
.twoLineCls {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  /* line-clamp: 1;  */
  -webkit-box-orient: vertical;
}
</style>